package it.marco.test.controller;

import it.marco.test.dm.User;
import it.marco.test.service.UserService;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@RequestMapping(value="/admin/users")
@SessionAttributes("user")
public class UserController {
	
	@Autowired
	private UserService/*<User, String>*/ serv;
	
//	@Autowired
//	private TestService s;
//	
//	@Autowired
//	private Validator validator;
//	
//	public void setValidator(Validator validator) {  
//        this.validator = validator;  
//	}  
	
	@RequestMapping(method=RequestMethod.GET)
	public String getListaUtenti(ModelMap model){
		List<User> lp = serv.findAll();
		
		model.addAttribute("listaUtenti",lp);
		
		
		return "utenti";
//		return new ModelAndView("index","test", "Ciao a tutti");
	}
	
	@RequestMapping(method=RequestMethod.GET, value={"new"})
	public String nuovoUtente(ModelMap model){
		User u = new User();
		model.addAttribute("user",u);
		return "editUtente";
	}
	
	@RequestMapping(method=RequestMethod.GET, params={"id"})
	public String dettagliUtente(@RequestParam("id") String id, ModelMap model){
		User a = new User();
		a.setUserId(id);
		User u = serv.find(id);
		model.addAttribute("user",u);
		return "editUtente";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String salva(@Valid @ModelAttribute("user") User u, BindingResult result){
		Md5PasswordEncoder pe =new Md5PasswordEncoder();
		u.setPassword(pe.encodePassword(u.getPassword(), u.getUserId()));
		//TestService s = new TestService();
		serv.saveOrUpdate(u);  //.saveOrUpdate(u);
		//s.testUser(u);
		return "utenti";
	}
}
